import axios from 'axios'
import querystring from 'querystring'
import {useUserStore} from '../store/user'


const errorHandle=(status:any,info:any)=>{
     switch(status){
         case 400:
             console.log('语义错误')
             break;
         case 401:
             console.log('token失效')
             break;
         case 403:
             console.log('服务器拒绝访问')
             break;
         case 404:
             console.log('请求地址错误')
             break;
         case 500:
             console.log('服务器遇到意外')
             break;
         case 502:
             console.log('服务器无响应')
             break;
         default:
             console.log(info)
             break;
     }
}

const instance = axios.create({
    timeout: 5000,
})

instance.interceptors.request.use(config => {
    if (config.method === 'post') {
        if (config.data) {
            config.data = querystring.stringify(config.data)
        }
    }
    return config
}, error => {
    console.log(error)
    return Promise.reject(error)
})

instance.interceptors.response.use(response => {
    if (response.status === 200) {

        return response.data
    } else {
        const userStore=useUserStore();
        errorHandle(response.status, response.data.message)
        return Promise.reject(response)
    }
}, error => {
    const { response } = error
    if(response){
        errorHandle(response.status, response.info)
        return Promise.reject(response);
    }else{
        console.log('网络连接失败，请检查网络设置');
        return Promise.reject(error);
    }
})

export default instance
